package com.atguigu.demojuc.chap05;

import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author njg
 * @version 1.0
 * @date 2025/6/17 16:04
 */
//六辆车抢三个车位
public class SemaphoreDemo {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(3);
        for (int i = 1; i <= 6; i++) {
            new Thread(() -> {
                try {
                    semaphore.acquire(); //占用资源，只有获取到信号才会使信号量permits减一，否则会一直阻塞下去
                    System.out.println(Thread.currentThread().getName() + "\t" + "抢到车位");
                    TimeUnit.SECONDS.sleep(new Random().nextInt(5));
                    System.out.println(Thread.currentThread().getName() + "\t" + "驶离车位");
                    semaphore.release(); //释放资源,增加信号量（+1）
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }, "车辆" + i).start();

        }
    }
}
